package com.jijuxie.message.service.impl;

import com.jijuxie.system.domain.SysMessage;
import com.jijuxie.system.domain.SysMessageTemplate;
import com.jijuxie.system.service.ISysMessageService;
import com.jijuxie.system.service.ISysMessageTemplateService;
import com.jijuxie.message.service.IMessagePushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class MessagePushServiceImpl implements IMessagePushService {

    @Autowired
    private ISysMessageService messageService;

    @Autowired
    private ISysMessageTemplateService templateService;

    @Override
    @Async
    public void pushMessage(String code, Long userId, Map<String, Object> params) {
        // 1. 参数校验
        if (code == null || userId == null) {
            throw new IllegalArgumentException("消息编码和用户ID不能为空");
        }

        // 2. 获取模板
        SysMessageTemplate template = templateService.getByCode(code);
        if (template == null || !"0".equals(template.getStatus())) {
            throw new RuntimeException("消息模板不存在或已停用：" + code);
        }

        // 3. 替换模板参数
        String title = replaceParams(template.getTitle(), params);
        String content = replaceParams(template.getContent(), params);

        // 4. 创建消息
        SysMessage message = new SysMessage();
        message.setUserId(userId);
        message.setTitle(title);
        message.setContent(content);
        message.setType(template.getType());

        // 5. 发送消息
        messageService.sendMessage(message);
    }

    @Override
    @Async
    public void pushMessageBatch(String code, List<Long> userIds, Map<String, Object> params) {
        for (Long userId : userIds) {
            pushMessage(code, userId, params);
        }
    }

    private String replaceParams(String content, Map<String, Object> params) {
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                content = content.replace("{" + entry.getKey() + "}", 
                        String.valueOf(entry.getValue()));
            }
        }
        return content;
    }
} 